<template>
  <div class="root-login">
    <div class="login-box">
      <div class="logo-row content-center">
        <img class="logo" src="@/assets/logo.png">
      </div>
      <a-form :form="form" @submit="handleSubmit">
        <a-form-item class="a-form-item">
          <a-input v-decorator="[
              'username',
              {rules: [{ required: true, message: '请输入你的帐号' }]}
            ]"
            placeholder="请输入你的帐号">
            <a-icon slot="prefix" type="user"/>
          </a-input>
        </a-form-item>
        <a-form-item class="a-form-item">
          <a-input type="password" v-decorator="[
              'password',
              {rules: [{ required: true, message: '请输入密码' }]}
            ]"
            placeholder="请输入密码">
            <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
          </a-input>
        </a-form-item>
        <a-form-item class="a-form-item" >
          <a-row type="flex">
              <a-col :span="14" :order="1">
                <a-input v-decorator="[
                    'validateCode',
                    {rules: [{ required: true, message: '请输入验证码' }]}
                  ]"
                  placeholder="请输入验证码">
                </a-input>
              </a-col>
              <a-col :span="10" :order="2">
                <img class="validate-code" @click="refreshCode" :src="validateCodeUrl">
              </a-col>
            </a-row>
        </a-form-item>
        <a-form-item class="a-form-item">
          <a-button type="primary" ghost html-type="submit" class="login-form-button">登录</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import {Form, Input, Icon, Button, Row, Col} from 'ant-design-vue'
Vue.component(Form.name, Form)
Vue.component(Form.Item.name, Form.Item)
Vue.component(Input.name, Input)
Vue.component(Icon.name, Icon)
Vue.component(Button.name, Button)
Vue.component(Row.name, Row)
Vue.component(Col.name, Col)
export default {
  name: 'Login',
  beforeCreate () {
    this.form = this.$form.createForm(this)
  },
  data () {
    const key = Math.random()
    return {
      cacheKey: key,
      validateCodeUrl: this.$env.validateCodeUrl(key)
      // form: this.$form.createForm(this)
    }
  },
  methods: {
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          // console.log('Received values of form: ', values)
          this.login(values)
        }
      })
    },
    login (values) {
      values.cacheKey = this.cacheKey
      this.$common.login(values)
        .then((res) => {
          this.$message.success('登录成功')
          window.localStorage.setItem('token', JSON.stringify(res.data))
          this.$store.dispatch('dictionary/getDictionarys')
          this.$store.dispatch('user/getCurrentUser')
          window.history.length > 1
            ? this.$router.go(-1)
            : this.$router.push('/')
        }).catch((error) => {
          if (error.response) {
            if (error.response.status === 500 && error.response.data.message) {
              this.refreshCode()
              this.$message.error(error.response.data.message)
              return
            }
            if (error.response.status === 400 && error.response.data.error === 'invalid_validate_code') {
              this.refreshCode()
              this.$message.error(error.response.data.message)
              return
            }
            if (error.response.status === 400 && error.response.data.error === 'invalid_grant') {
              this.refreshCode()
              this.$message.error('帐号或是密码错误')
            }
            if (error.response.status === 401 && error.response.data.error === 'duplicate_logon') {
              this.$confirm({
                title: '帐号已经在其他设备或终端登录',
                content: '帐号已经在其他设备或终端登录，点"确定"继续登录',
                onOk () {
                  return new Promise((resolve, reject) => {
                    // setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
                    values.continueLogin = true
                    this.login(values)
                    resolve()
                  }).catch(() => console.log('Oops errors!'))
                },
                onCancel () {
                  this.refreshCode()
                }
              })
            }
          }
        }).then(function (e) {
          console.log(e)
          // always executed
          console.log('always executed')
        })
    },
    refreshCode () {
      this.cacheKey = Math.random()
      this.validateCodeUrl = this.$env.validateCodeUrl(this.cacheKey)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.root-login {
  width: 100%;
  height: 100%;
  display:flex;
  flex-direction:column;
  justify-content: center;
  align-items: center;
}

.logo {
  width: 50%;
}
.login-form-button {
  width: 100%;
}
.a-form-item {
  margin-bottom: 0px;
}
.validate-code {
  float: right;
  cursor: pointer;
}

/* 屏幕宽度小于767个象素时应用的CSS样式*/
@media (max-width: 415px) {
  .login-box {
    margin-top: 10vh;
    width: 90vw;
    background-color:white;
    padding: 20px;
    border-radius: 10px;
  }
}
@media (min-width: 416px) {
  .login-box {
    margin-top: 10vh;
    width: 20vw;
    background-color:white;
    padding: 20px;
    border-radius: 10px;
  }
}
</style>
